/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab5sum;


import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Daryna_Ragimova
 */
public class Calculation {
    private final int threadsNumber;
    private final int N;
    private ExecutorService executorService;
    private CompletionService<Double> threads;
    private Double sum = 0.0;
    public Calculation(int n, int threadsNumber) {
        this.N = n;
        this.threadsNumber = threadsNumber;
        executorService = Executors.newFixedThreadPool(threadsNumber); 
        threads = new ExecutorCompletionService<Double>(executorService);
    }
    
    
    public double process() {
        int forProcess = (2 * N + 1) / threadsNumber;
        if ((2 * N + 1) % threadsNumber > forProcess / 2) {
            forProcess++;
        }
        for (int i = 0; i < threadsNumber; i++) {
            int first = -N + forProcess * i;
            int last = -N + forProcess * (i + 1);
            if (last >= N) {
                last = N + 1;
            }
            Callable worker = new WorkerThread(first, last);
            threads.submit(worker);
        }
        for (int i = 0; i < threadsNumber; i++) {
            try {
                Future<Double> result = threads.take();
                sum += result.get();
            } catch (ExecutionException ex) {
                Logger.getLogger(Calculation.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InterruptedException ex) {
                Logger.getLogger(Calculation.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        executorService.shutdown();
        return sum;
    }

}
